<?php

namespace App\V3\Api\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Api\BaseController;
use App\V3\Api\Services\CheckStorageManageService;
use Illuminate\Support\Facades\Validator;
use App\Helper\Utils\TimeUtil;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\DB;
use App\V3\Api\Models\CheckStorageManageModel;
use function GuzzleHttp\json_decode;
use Mavinoo\Batch\Batch;
use App\V3\Api\Models\StorageManageModel;
use App\Api\Models\MaterielTypeModel;

class CheckStorageManageController extends BaseController
{

    //仓库列表
    public function storageList(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '参数`pageSize`丢失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`丢失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        return $this->success(CheckStorageManageService::getStorageList($this->getMainUserId(), $data));
    }

    //仓库及商品列表
    public function getStorageGoodsList(Request $request){
          //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'storage_id.required' => '`仓库id`缺失',
            'storage_id.integer' => '`仓库id`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        $list = CheckStorageManageService::getStorageGoodsList($request->storage_id, $data);

        return $this->success($list);

    }

     public function addCheckStorageGoods(Request $request){

         //参数验证
         $validator = Validator::make($data = $request->all(), [
             'storage_id' => 'required|numeric',//仓库id
             'sg_type' => [
                 'required',
                 Rule::In([1,2])
             ],//盘点类型1:整仓库;2:商品;
         ],[
             'storage_id.required'=>'仓库主键`id`缺失',
             'storage_id.numeric' =>'仓库主键`id`必须为整数',
             'sg_type.required'   =>'盘点类型，必要参数',
             'sg_type.in'         =>'盘点类型:1、整仓库;2、商品',
         ]);
         //参数错误响应
         if($info = $validator->errors()->first()) {
             return response()->json([
                 'code' => 1,
                 'msg' => $info,
                 'data' => '',
             ]);
         }
         $arr = array();
         if(!empty($data['goods_info'])){

             $goodsInfo = json_decode($data['goods_info'],true);
             $check_no  = $this->getMainUserId().TimeUtil::getMillisecond();
             foreach ($goodsInfo as &$v){
                 if(!empty($v['check_num']) && getDecimalPointLeng($v['check_num'])>7) return $this->fail('','盘点数小数点后，不能超过6位数字。');
                 if(!empty($v['yk_num']) && getDecimalPointLeng($v['yk_num'])>7) return $this->fail('','盈亏数量小数点后，不能超过6位数字。');
                 if(!empty($data['is_cover'])){

                 $v['is_cover']   = $data['is_cover'];
                 }
                 $v['check_time'] = time();
                 $v['created_at'] = time();
                 $v['sg_type']    = $data['sg_type'];
                 $v['user_id']    = $this->getUserId();
                 $v['storage_id'] = $data['storage_id'];
                 $v['main_id']    = $this->getMainUserId();
                 $v['check_no']   = $check_no;
                 $arr[]=[
                     'id'=>$v['storage_manage_id'],
                     'in_storage_num'=>$v['check_num'],
                     'virtual_storage_num'=>$v['check_num']
                 ];
             }
             DB::beginTransaction();
             try {
                 CheckStorageManageModel::insert($goodsInfo);
                 if(!empty($data['is_cover'])){                 
                        batch()->update(new StorageManageModel(),$arr,'id');                    
                 }
                 $this->log('新建整库盘点', $data);
                 DB::commit();
                 return $this->success();
             } catch (\Exception $e) {
                 DB::rollBack();
                 $this->fail('',$e->getMessage());
             }
         }
    }

    /**
     * 修改仓库和商品盘点数
     * @param check_no 盘点编号
     * @param is_cover 是否开启覆盖库存
     * @param storage_manage_id  库存id
     * @param type_id            物料类型名称/型号id
     * @param yk_flag            物料类型名称/型号id
     * @param check_num  物料类型名称/型号id
     * @param yk_num  物料类型名称/型号id
     */
    public function updCheckStorageGoods(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'check_no' =>'required|integer',//盘点编号
        ],[
            'check_no.required' => '`盘点编号`必要参数',
            'check_no.integer' => '`盘点编号`只能为数字',
        ]);
        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $info = CheckStorageManageModel::select('check_no','storage_id')
                ->where('check_no',$data['check_no'])->first()->toArray();

        if(empty($info)) return $this->fail('','没有找到，要修改的盘点数据。');

        $arr = array();

            if(!empty($data['goods_info'])){

                $goodsInfo = json_decode($data['goods_info'],true);
                DB::beginTransaction();
                try {
                foreach ($goodsInfo as &$v){
                    
                    if(!empty($v['check_num']) && getDecimalPointLeng($v['check_num'])>7) return $this->fail('','盘点数小数点后，不能超过6位数字。');
                    if(!empty($v['yk_num']) && getDecimalPointLeng($v['yk_num'])>7) return $this->fail('','盈亏数量小数点后，不能超过6位数字。');

                    if(!empty($data['is_cover'])){

                        $v['is_cover']   = $data['is_cover'];
                    }

                    $v['updated_at'] = time();
                    $condition['type_id']    = $v['type_id'];
                    $condition['check_no']   = $info['check_no'];
                    $condition['storage_id'] = $info['storage_id'];
                    $condition['storage_manage_id'] = $v['storage_manage_id'];
                    CheckStorageManageModel::where($condition)->update($v);

                    $arr[]=[
                        'id'=>$v['storage_manage_id'],
                        'in_storage_num'=>$v['check_num'],
                        'virtual_storage_num'=>$v['check_num']
                    ];
                }

                if(!empty($data['is_cover'])){

                        batch()->update(new StorageManageModel(),$arr,'id');
                }
                $this->log('新建整库盘点', $data);
                DB::commit();
                return $this->success();
            } catch (\Exception $e) {
                DB::rollBack();
                $this->fail('',$e->getMessage());
            }
        }
    }

    /**
     * 通过批次号查询商品信息（扫一扫）
     * @param Request $request
     */
    public function readBatchNo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' =>'required',//条码信息
        ],[
            'batch_no.required' => '参数`条码信息`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(
            CheckStorageManageService::readBatchNo($data)
            );
    }
    /**
     * 盘点仓库和商品列表
     * @param Request $request
     */
    public function getCheckList(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
        ],[
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $condition['a.main_id'] = $this->getMainUserId();
        $keyword = empty($request->keyword)?'':$request->keyword;
        $list = CheckStorageManageService::checkList($condition,$data,$keyword);
        return $this->success($list);

    }

    /**
     * 盘点盈亏列表
     * @param Request $request
     */
    public function getCheckYkGoodsList(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer|min:1',//页面大小
            'currentPage' =>'required|integer',//当前页
            'check_no' =>'required|integer',//盘点编号
          /*   'yk_flag' => [
                'required',
                Rule::In([1,2])
            ],//盘点类型1:整仓库;2:商品; */
        ],[
            'check_no.required' => '`盘点编号`必要参数',
            'check_no.integer' => '`盘点编号`只能为数字',
            'pageSize.required' => '`页面大小`缺失',
            'pageSize.integer' => '`页面大小`只能为数字',
            'pageSize.min' => '`页面大小`默认最小仅能为1',
            'currentPage.required' => '`页面大小`缺失',
            'currentPage.integer' => '`页面大小`只能为数字',
            'currentPage.min' => '`页面大小`默认最小仅能为1',
           /*  'yk_flag.required'         =>'盘点类型，必要参数',
            'yk_flag.in'         =>'盘点类型:1、盈;2、亏', */
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }
        $condition['a.main_id'] = $this->getMainUserId();
        $keyword = empty($request->keyword)?'':$request->keyword;
        $list = CheckStorageManageService::checkSkGoodsList($condition,$data,$keyword);
     if(!empty($list['data'])){
          foreach ($list['data'] as $k=>$v){
              $list['data'][$k]['shelf_name']    = !empty($v['shelf_name'])?$v['shelf_name']:"";
              $list['data'][$k]['location_name'] = !empty($v['location_name'])?$v['location_name']:"";
              if($v['is_cover'] == 1){
                  if($v['yk_flag'] == 2){
                      $list['data'][$k]['in_storage_num'] =$v['check_num']+$v['yk_num'];
                  }elseif($v['yk_flag'] == 1){
                      $list['data'][$k]['in_storage_num'] =$v['check_num']-$v['yk_num'];
                  }
              }
          }  
        }
        return $this->success($list);

    }
}
